package com.cellulam.framework.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;

import java.time.ZoneId;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DelayScheduleTask implements Delayed {

    private ScheduleTask task;

    private long expectedBeginTime;

    public DelayScheduleTask(ScheduleTask task, int delayMills) {
        this.init(task, delayMills);
    }

    public DelayScheduleTask(ScheduleTask task) {
        if (task.getScheduleStartTime() == null) {
            this.init(task, 100 + this.getRandomDelta());
        } else {
            this.init(task, task.getScheduleStartTime()
                    .atZone(ZoneId.systemDefault())
                    .toInstant()
                    .toEpochMilli());
        }
    }

    private void init(ScheduleTask task, int delayMills) {
        this.init(task, delayMills + System.currentTimeMillis());
    }

    private void init(ScheduleTask task, long expectedBeginTime) {
        this.task = task;
        this.expectedBeginTime = expectedBeginTime;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long diff = expectedBeginTime - System.currentTimeMillis();
        long convert = unit.convert(diff, TimeUnit.MILLISECONDS);
        log.debug("getDelay convert is {}", convert);
        return convert;
    }

    @Override
    public int compareTo(Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    private long getRandomDelta() {
        return RandomUtils.nextLong(10, 1000);
    }

    public ScheduleTask getTask() {
        return this.task;
    }
}
